#include "config.h"

#include <time.h>

#include "ms2lstat.h"

char	*lparser_modpath;
ECMBOOL	mod_has_error;
char	*mod_errmsg;
ecm_uint32	wday_start;

ecm_uint32	start_tick;
ecm_uint32	end_tick;

static ecm_ptr_t	handle;

lparser_op_t	*lparser_op;

void
lp_error(const char *fmt, ...)
{
	va_list	ap;

	ecm_free(mod_errmsg);
		
	va_start(ap, fmt);
	ecm_vasprintf(&mod_errmsg, fmt, ap);
	va_end(ap);

	mod_has_error = ECM_TRUE;
}

ecm_uint32
lp_get_timetick(const char *datetime_str)
{
	ecm_uint32	year, month, day;
	ecm_uint32	hh, mm, ss;
	struct tm	tm;
	time_t		t;

	if (ecm_sscanf(datetime_str, "%u-%u-%u %u:%u:%u", &year, &month, &day, &hh, &mm, &ss) != 6)
		return 0;

	if (month == 0 || month > 12 || year < 1900 || day > 31 || hh > 23 || mm > 59 || ss > 59)
		return 0;

	ecm_memset(&tm, 0, sizeof(tm));
	tm.tm_sec = ss;
	tm.tm_min = mm;
	tm.tm_hour = hh;
	tm.tm_mday = day;
	tm.tm_mon = month - 1;
	tm.tm_year = year - 1900;
	t = mktime(&tm);
#ifndef _WIN32
	t += tm.tm_gmtoff;
#else
	t += 9;///TODO windows hack
#endif
	ecm_memset(&tm, 0, sizeof(tm));
#ifndef _WIN32
	localtime_r(&t, &tm);
#else
	localtime_s(&tm, &t);
#endif
	if (start_tick == 0) {
		tm.tm_sec = 0;
		tm.tm_min = 0;
		tm.tm_hour = 0;
		wday_start = tm.tm_wday;
		start_tick = mktime(&tm) - 1;
	}

	end_tick = t;

	return (t - start_tick);
}

ecm_uint32
lp_get_mid(const char *uri)
{
	return get_media_id(uri);
}

ecm_uint32
lp_get_cid(const char *client)
{
	return get_client_id(client);
}

ecm_uint32
lp_get_pid(const char *playerstr)
{
	return get_player_id(playerstr);
}

void
lp_update_media_info(ecm_uint32 mid, ecm_uint64 length, ecm_uint64 size)
{
	update_media_info(mid, length, size);
}

static ECMBOOL
load_module(void)
{
	if ((handle = ecm_dlopen(lparser_modpath, ECM_FALSE)) == NULL) {
		ERR("%s: log parser module loading failed: %s", lparser_modpath, ecm_dlerror());
		return ECM_FALSE;
	}
	lparser_op = (lparser_op_t *)ecm_dlsym(handle, "lparser_op");
	if (lparser_op == NULL) {
		ERR("%s: invalid log parser module", lparser_modpath);
		ecm_dlclose(handle);
		handle = NULL;
		return ECM_FALSE;
	}

	return ECM_TRUE;
}

ECMBOOL
init_mod(void)
{
	return load_module();
}
